"use strict";

const utils = require("./utils");
const bind = require("./helpers/bind");
const Axios = require("./core/Axios");
const mergeConfig = require("./core/mergeConfig");
const defaults = require("./defaults");

/**
 * 创建一个axios实例
 * @param {Object} defaultConfig 默认配置
 * @returns {Axios} 一个新的Axios实例
 */
function createInstance(defaultConfig) {
  // 创建一个axios上下文
  const context = new Axios(defaultConfig);
  // 将axios实例的request对象绑定axios上下文
  const instance = bind(Axios.prototype.request, context);

  // 将axios实例拷贝到instance并绑定axios上下文
  utils.extend(instance, Axios.prototype, context);

  // 将axios上下文拷贝到instance
  utils.extend(instance, context);

  return instance;
}

// 创建一个默认axios实例，用于导出
const axios = createInstance(defaults);

// 暴露Axios类，允许类继承
axios.Axios = Axios;

// 工厂方法：创建一个新实例
axios.create = function create(instanceConfig) {
  return createInstance(mergeConfig(axios.defaults, instanceConfig));
};

// 暴露Cancel、CancelToken、isCancel
axios.Cancel = require("./cancel/Cancel");
axios.CancelToken = require("./cancel/CancelToken");
axios.isCancel = require("./cancel/isCancel");

// 暴露all/spread
axios.all = function all(promises) {
  return Promise.all(promises);
};
axios.spread = require("./helpers/spread");

module.exports = axios;

// 在Typescript中允许使用默认导入方法
module.exports.defaults = axios;
